//
//  LGCancerPatientFollowController.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2024/7/25.
//  癌症患者 -- 查看随访计划

#import "LGCancerPatientFollowController.h"
#import "LGLungFollowSendTaskCell.h"
//新增、修改随访计划
#import "LGLungFollowEditController.h"
#import "LGLungFollowSendTaskCell.h"
#import "DatePickerView.h"
#import "LGPickerView.h"
@interface LGCancerPatientFollowController ()<UITableViewDelegate,UITableViewDataSource,LGBottomButtonDelegate>
/**   */
@property (nonatomic , strong)LGBottomButtonView *bottomView;
/**   */
@property (nonatomic , strong)UITableView *tableView;
/**   */
@property (nonatomic , strong)UIButton *timeButton;
/**   */
@property (nonatomic , strong)UIButton *templateBtn;
/**   */
@property (nonatomic , strong)UIButton *editButton;
/**   */
@property (nonatomic , strong)NSArray *dataArray;
/**   */
@property (nonatomic , strong)NSArray *planArray;
/**  模版名称 */
@property (nonatomic , copy)NSString *templateName;
/**   */
@property (nonatomic , strong)UILabel *descLabel;
/**   */
@property (nonatomic , copy)NSString *descStr;
/**   */
@property (nonatomic , copy)NSString *addType;
/**  模版列表 */
@property (nonatomic , strong)NSArray *modelArray;
/**   */
@property (nonatomic , strong)NSArray *modelNameArray;
/**   */
@property (nonatomic , strong)NSArray *patientArray;

/**   */
@property (nonatomic , strong)NSDateFormatter *formatter;

@end

@implementation LGCancerPatientFollowController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"随访计划";
    self.descStr = @"";
    self.planid = (_planid && _planid.length>0)?_planid:@"";
    self.levelid = (_levelid && _levelid.length>0)?_levelid:@"";
    self.patientArray = (_patientid && _patientid.length>0)?@[self.patientid]:@[];
    self.addType = (_patientid && _patientid.length>0)?@"one":@"";
    self.templateName = @"随访计划模板名称";
    [self.view addSubview:self.tableView];
    if (self.canEdit == YES) {
        self.tableView.frame = CGRectMake(0, 0, Screen_W, Screen_H-topBarHeight-viewPix(65)-bottomSafeBarHeight/4.0);
        [self.view addSubview:self.bottomView];
    }
    [self requestData];
}

-(void)requestData{
    [RequestUtil withPOST:@"/doctor/Careplan/carePlanTemplateDetail" parameters:@{@"level_id":self.levelid,@"careplan_id":self.planid,@"base_date":self.baseDate,@"patient_ids":self.patientArray,@"add_type":self.addType} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if (code == 200) {
            self.planid = LGNSString(returnData[@"careplan_id"]);
            self.baseDate = LGNSString(returnData[@"base_date"]);
            self.modelArray = returnData[@"temp_lists"];
            self.planArray = returnData[@"careplans_data"];
            self.dataArray = returnData[@"careplans_lists"];
            self.patientArray = returnData[@"patient_ids"];
            [self.tableView reloadData];
        }
    } error:^(NSError *error) {
        
    }];
}

-(void)setPatientArray:(NSArray *)patientArray{
    _patientArray = patientArray;
}

-(void)setBaseDate:(NSString *)baseDate{
    _baseDate = baseDate;
    [self.timeButton setTitle:baseDate forState:UIControlStateSelected];
    self.timeButton.selected = (baseDate.length>0)?YES:NO;
}

-(void)setModelArray:(NSArray *)modelArray{
    _modelArray = modelArray;
    if (modelArray.count == 0) {
        self.descStr = @"";
        self.templateName = @"未匹配到随访模版";
        self.modelNameArray = @[];
    }else{
        NSMutableArray *nameArray = [NSMutableArray array];
        for (NSInteger i=0; i<modelArray.count; i++) {
            NSDictionary *tempDic = modelArray[i];
            [nameArray addObject:LGNSString(tempDic[@"title"])];
            if ([self.planid isEqualToString:LGNSString(tempDic[@"careplan_id"])]) {
                self.templateName = LGNSString(tempDic[@"title"]);
                self.descStr = LGNSString(tempDic[@"desc"]);
            }
        }
        self.modelNameArray = nameArray;
    }
    self.templateBtn.hidden = (modelArray.count>1)?NO:YES;
    self.descLabel.text = self.descStr;
}

//选择开始时间
-(void)selectStartTimeAction{
    if (self.canEdit == NO) return;
    DatePickerView *pickerView = [[DatePickerView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H)];
    pickerView.title = @"随访开始时间";
    pickerView.beginDate = [self.formatter stringFromDate:[NSDate date]];
    pickerView.currentDate = self.baseDate;
    [[ObjectTool mainWindow] addSubview:pickerView];
    __weak typeof(self) weakSelf = self;
    pickerView.selectDate = ^(NSString *date) {
        weakSelf.baseDate = date;
        [RequestUtil withPOST:@"/doctor/Careplan/carePlanTemplateDetail" parameters:@{@"level_id":self.levelid,@"careplan_id":weakSelf.planid,@"base_date":weakSelf.baseDate,@"patient_ids":self.patientArray,@"add_type":weakSelf.addType,@"careplans_data":[ObjectTool objectToJson:weakSelf.planArray]} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
            if (code == 200) {
                weakSelf.planid = LGNSString(returnData[@"careplan_id"]);
                weakSelf.baseDate = LGNSString(returnData[@"base_date"]);
                weakSelf.modelArray = returnData[@"temp_lists"];
                weakSelf.planArray = returnData[@"careplans_data"];
                weakSelf.dataArray = returnData[@"careplans_lists"];
                weakSelf.patientArray = returnData[@"patient_ids"];
                NSString *title = (self.dataArray.count == 0)?@"创建随访计划":@"修改随访计划";
                [weakSelf.editButton setTitle:title forState:UIControlStateNormal];
                [weakSelf.tableView reloadData];
            }
        } error:^(NSError *error) {
            
        }];
    };
}

//切换随访计划
-(void)selectTemplateAction{
    if (self.modelNameArray.count == 0) {
        [self requestData];
        [TooltipView showMessage:@"暂无匹配的随访模版" offset:0];
        return;
    }
    LGPickerView *pickerView = [[LGPickerView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H)];
    pickerView.titleLabel.text = @"随访计划";
    pickerView.selectStr = self.templateName;
    pickerView.pickArry = @[self.modelNameArray];
    [[ObjectTool mainWindow] addSubview:pickerView];
    __weak typeof(self) weakSelf = self;
    pickerView.selectPickViewIndex = ^(NSArray *indexArray) {
        NSInteger index = [indexArray[0] integerValue];
        NSDictionary *tempDic = weakSelf.modelArray[index];
        weakSelf.planid = LGNSString(tempDic[@"careplan_id"]);
        weakSelf.templateName = LGNSString(tempDic[@"title"]);
        weakSelf.descStr = LGNSString(tempDic[@"desc"]);
        [RequestUtil withPOST:@"/doctor/Careplan/carePlanTemplateDetail" parameters:@{@"level_id":self.levelid,@"careplan_id":weakSelf.planid,@"base_date":weakSelf.baseDate,@"patient_ids":self.patientArray,@"add_type":weakSelf.addType,@"careplans_data":[ObjectTool objectToJson:weakSelf.planArray]} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
            if (code == 200) {
                weakSelf.planid = LGNSString(returnData[@"careplan_id"]);
                weakSelf.baseDate = LGNSString(returnData[@"base_date"]);
                weakSelf.modelArray = returnData[@"temp_lists"];
                weakSelf.planArray = returnData[@"careplans_data"];
                weakSelf.dataArray = returnData[@"careplans_lists"];
                weakSelf.patientArray = returnData[@"patient_ids"];
                NSString *title = (self.dataArray.count == 0)?@"创建随访计划":@"修改随访计划";
                [weakSelf.editButton setTitle:title forState:UIControlStateNormal];
                [weakSelf.tableView reloadData];
            }
        } error:^(NSError *error) {
            
        }];
    };
}

//修改随访计划
-(void)editFollowUpAction{
    LGLungFollowEditController *controller = [[LGLungFollowEditController alloc]init];
    controller.dataArray = self.planArray;
    [self.navigationController pushViewController:controller animated:YES];
    __weak typeof(self) weakSelf = self;
    controller.planEditSuccess = ^(NSArray * _Nonnull dataArray) {
        weakSelf.planArray = dataArray;
        [RequestUtil withPOST:@"/doctor/Careplan/carePlanTemplateDetail" parameters:@{@"level_id":self.levelid,@"careplan_id":self.planid,@"base_date":self.baseDate,@"patient_ids":self.patientArray,@"add_type":self.addType,@"careplans_data":[ObjectTool objectToJson:dataArray]} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
            if (code == 200) {
                weakSelf.planid = LGNSString(returnData[@"careplan_id"]);
                weakSelf.baseDate = LGNSString(returnData[@"base_date"]);
                weakSelf.modelArray = returnData[@"temp_lists"];
                weakSelf.planArray = returnData[@"careplans_data"];
                weakSelf.dataArray = returnData[@"careplans_lists"];
                weakSelf.patientArray = returnData[@"patient_ids"];
                NSString *title = (self.dataArray.count == 0)?@"创建随访计划":@"修改随访计划";
                [weakSelf.editButton setTitle:title forState:UIControlStateNormal];
                [weakSelf.tableView reloadData];
            }
        } error:^(NSError *error) {
            
        }];
    };
}


//发送随访
-(void)bottomButtonTouched{
    [RequestUtil withPOST:@"/doctor/Careplan/createCarePlanFromTemplate" parameters:@{@"level_id":self.levelid,@"patient_ids":self.patientArray,@"careplans_data":[ObjectTool objectToJson:self.planArray],@"base_date":self.baseDate,@"careplan_id":self.planid} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if (code == 200) {
            [TooltipView showMessage:@"发送成功" offset:0];
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [TooltipView showMessage:message offset:0];
        }
    } error:^(NSError *error) {
        
    }];
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 1) {
        return self.dataArray.count;
    }
    return 0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1) {
        LGLungFollowSendTaskCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.dataDic = self.dataArray[indexPath.row];
        cell.index = indexPath.row+1;
        return cell;
    }
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        CGFloat descHeight = [self.descStr textHeightWithFont:LGFont(14) maxWidth:Screen_W-viewPix(56)];
        return viewPix(65)+descHeight;
    }
    return viewPix(48);
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    CGFloat height = viewPix(48);
    if (section == 1) {
        height = [self.descStr textHeightWithFont:LGFont(14) maxWidth:Screen_W-viewPix(56)]+viewPix(65);
    }
    LGCornerHeaderView *headView = [[LGCornerHeaderView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, height)];
    headView.topMargin = viewPix(8);
    NSArray *iconArray = @[@"肺癌随访-时间",@"肺癌随访-名称"];
    UIImageView *iconView = [[UIImageView alloc]initWithFrame:CGRectMake(viewPix(28), viewPix(24), viewPix(24), viewPix(24))];
    iconView.image = [UIImage imageNamed:iconArray[section]];
    [headView addSubview:iconView];
    NSArray *titleArray = @[@"随访开始时间",self.templateName];
    UILabel *titleLabel = [UILabel lableWithText:titleArray[section] colorString:@"#333333" textFont:LGFontWeight(16, UIFontWeightMedium) textAlignment:NSTextAlignmentLeft lines:2];
    [headView addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(iconView.mas_right).offset(viewPix(6));
        make.centerY.equalTo(iconView);
        make.right.lessThanOrEqualTo(headView).offset(-viewPix(160));
    }];
    if (section == 0){
        [headView addSubview:self.timeButton];
    }else{
        if (self.canEdit == YES) {
            [headView addSubview:self.templateBtn];
            [headView addSubview:self.editButton];
            [headView addSubview:self.descLabel];
            [self.templateBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.centerY.equalTo(titleLabel);
                make.right.equalTo(titleLabel).offset(viewPix(16));
                make.height.equalTo(@(viewPix(30)));
            }];
            [self.descLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(titleLabel.mas_bottom).offset(viewPix(7));
                make.left.equalTo(iconView);
                make.right.equalTo(self.editButton);
            }];
        }else{
            [headView addSubview:self.descLabel];
            [self.descLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(titleLabel.mas_bottom).offset(viewPix(7));
                make.left.equalTo(iconView);
                make.right.equalTo(headView).offset(-viewPix(28));
            }];
        }
    }
    
    if (self.canEdit == YES) {
        UIImageView *tipView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"grayTip16"]];
        [headView addSubview:tipView];
        [tipView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(headView).offset(-viewPix(24));
            make.centerY.equalTo(iconView);
            make.width.height.equalTo(@(viewPix(16)));
        }];
    }
    
    return headView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return viewPix(24);
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    LGCornerFooterView *footView = [[LGCornerFooterView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(24))];
    footView.bottomMargin = viewPix(8);
    return footView;
}

-(UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H-topBarHeight) style:UITableViewStyleGrouped];
        [_tableView registerClass:[LGLungFollowSendTaskCell class] forCellReuseIdentifier:@"cell"];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.dataSource = self;
        _tableView.delegate = self;
    }
    return _tableView;
}

-(UIButton *)timeButton{
    if(!_timeButton){
        _timeButton = [UIButton buttonWithTitle:@"请选择" titleFont:LGFont(16) normalColor:@"#999999" selectColor:@"#282828"];
        _timeButton.frame = CGRectMake(viewPix(200), viewPix(16), Screen_W-viewPix(240), viewPix(40));
        _timeButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        [_timeButton addTarget:self action:@selector(selectStartTimeAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _timeButton;
}

-(UIButton *)editButton{
    if(!_editButton){
        _editButton = [UIButton buttonWithTitle:@"修改随访计划" titleFont:LGFont(16) normalColor:@"#999999" selectColor:@"#282828"];
        _editButton.frame = CGRectMake(viewPix(220), viewPix(16), Screen_W-viewPix(260), viewPix(40));
        _editButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        [_editButton addTarget:self action:@selector(editFollowUpAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _editButton;
}

-(UIButton *)templateBtn{
    if(!_templateBtn){
        _templateBtn = [UIButton buttonWithImage:@"blackTipDown16" selectImage:@"blackTipDown16"];
        _templateBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        [_templateBtn addTarget:self action:@selector(selectTemplateAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _templateBtn;
}

-(UILabel *)descLabel{
    if(!_descLabel){
        _descLabel = [UILabel lableWithText:@"" colorString:@"#606266" textFont:LGFont(14) textAlignment:NSTextAlignmentLeft lines:0];
    }
    return _descLabel;
}

-(LGBottomButtonView *)bottomView{
    if(!_bottomView){
        _bottomView = [[LGBottomButtonView alloc] initWithTitle:@"发送随访" color:@"#5E8EF5" type:LGBottomButtonTypeBack frame:CGRectMake(0, kMaxY(self.tableView.frame), Screen_W, viewPix(65)+bottomSafeBarHeight/4.0)];
        [_bottomView setShadoWithColor:@"#EFEFEF" offset:CGSizeMake(0, 2) opacity:1 radius:0];
        _bottomView.delegate = self;
    }
    return _bottomView;
}

-(NSDateFormatter *)formatter{
    if(!_formatter){
        _formatter = [[NSDateFormatter alloc]init];
        _formatter.dateFormat = @"yyyy-MM-dd";
    }
    return _formatter;
}

@end
